package com.person.android.ui.fragments;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.person.android.dao.UIRenderParameter;
import com.person.android.formatts.R;
import com.person.android.resource.XMLReader;
import com.person.android.ui.activity.MainActivity;
import com.person.android.utils.LogUtils;
import com.person.android.utils.ToastUtils;
import com.person.android.widgets.SwitchButton;
import com.person.android.widgets.cutom_spinner.AbstractSpinnerAdapter;
import com.person.android.widgets.cutom_spinner.CustomSpinnerAdapter;
import com.person.android.widgets.cutom_spinner.CustomSpinnerData;
import com.person.android.widgets.cutom_spinner.SpinnerPopWindow;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhaokang on 2015/11/29.
 */
public class SettingFragment extends Fragment implements View.OnClickListener, AbstractSpinnerAdapter.IOnItemSelectListener, SwitchButton.OnChangeListener {

    private View mView;
    private Context mContext;

    private RelativeLayout mUIColorSetting;     //界面颜色下拉扩展区域
    private RelativeLayout mNavColorSetting;    //导航栏颜色下拉扩展区域

    private ImageButton mUIIbv;                 //界面颜色下拉小图标
    private ImageButton mNavIbv;                //导航栏颜色下拉小图标
    private TextView mUITxtView;                //界面颜色显示TV
    private TextView mNavTxtView;               //导航栏颜色设置TV
    private SpinnerPopWindow mUIPopWindow;      //界面颜色设置下拉菜单
    private SpinnerPopWindow mNavPopWindow;     //导航栏颜色设置下拉菜单
    private CustomSpinnerAdapter mUIAdapter;    //自定义UI下拉菜单适配器
    private CustomSpinnerAdapter mNavAdapter;   //自定义导航栏下拉菜单适配器

    private int mUIColorValue;                  //用于记录用户设置的界面颜色背景变量
    private int mNavColorValue;                 //用于记录用户设置的导航栏颜色背景变量
    private boolean mProtectedEye;              //用于记录用户设置的护眼模式变量

    private SwitchButton mSwitchButton;         //护眼模式开关
    private Button mSaveConfigureBtn;           //保存配置信息按钮
    private Button mClearTransformBtn;          //清空记录按钮

    private List<CustomSpinnerData> mColorList = new ArrayList<>();//颜色容器

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LogUtils.logInfo(LogUtils.FileListActivityFlag, "SettingFragment onCreateView...");
        mView = inflater.inflate(R.layout.fragment_setting, container, false);
        mContext = mView.getContext();
        findViews();
        setListeners();
        initialUIData();
        return mView;
    }

    @Override
    public void onStop() {
        super.onStop();
        LogUtils.logInfo(LogUtils.FileListActivityFlag, "SettingFragment onStop...");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtils.logInfo(LogUtils.FileListActivityFlag, "SettingFragment onDestroyView...");
    }

    private boolean mIsSavingConfiguration = false;

    //将配置信息写入到配置文件之中
    private int writeUIParameterConfigureInfo() {
        try {
            UIRenderParameter parameter = getUIRenderParameter();
            XMLReader.saveUIRenderParameter(mContext, parameter);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    private UIRenderParameter getUIRenderParameter() {
        UIRenderParameter renderParameter = new UIRenderParameter();
        renderParameter.mNavColorValue = mNavColorValue;
        renderParameter.mUIColorValue = mUIColorValue;
        renderParameter.mProEyeValue = mProtectedEye;
        return renderParameter;
    }

    private void initialUIData() {
        String[] names = getResources().getStringArray(R.array.color_name);
        UIRenderParameter parameter = XMLReader.getUIParameter(mContext);
        mNavColorValue = parameter.mNavColorValue;
        mUIColorValue = parameter.mUIColorValue;
        mProtectedEye = parameter.mProEyeValue;

        for (int i = 0; i < names.length; i++) {
            CustomSpinnerData object = new CustomSpinnerData();
            object.color = names[i];
            mColorList.add(object);
        }

        mSwitchButton.setOnOrOff(mProtectedEye);
        mUITxtView.setText(mColorList.get(mUIColorValue).color);
        mNavTxtView.setText(mColorList.get(mNavColorValue).color);

        mNavAdapter = new CustomSpinnerAdapter(mContext);
        mUIAdapter = new CustomSpinnerAdapter(mContext);

        mUIPopWindow = new SpinnerPopWindow(mContext);
        mUIPopWindow.setAdapter(mUIAdapter);
        mUIAdapter.refreshData(mColorList, mUIColorValue);
        mUIPopWindow.setItemListener(this);

        mNavPopWindow = new SpinnerPopWindow(mContext);
        mNavPopWindow.setAdapter(mNavAdapter);
        mNavAdapter.refreshData(mColorList, mNavColorValue);
        mNavPopWindow.setItemListener(this);

    }

    private void setListeners() {
        mUIIbv.setOnClickListener(this);
        mNavIbv.setOnClickListener(this);
        mUIColorSetting.setOnClickListener(this);
        mNavColorSetting.setOnClickListener(this);
        mSaveConfigureBtn.setOnClickListener(this);
        mClearTransformBtn.setOnClickListener(this);
    }

    private void findViews() {
        mColorList.clear();
        mUIIbv = (ImageButton) mView.findViewById(R.id.ui_color_ibv);
        mNavIbv = (ImageButton) mView.findViewById(R.id.nav_color_ibv);
        mSaveConfigureBtn = (Button) mView.findViewById(R.id.save_setting);
        mNavTxtView = (TextView) mView.findViewById(R.id.nav_color_spinner);
        mSwitchButton = (SwitchButton) mView.findViewById(R.id.light_switch);
        mUITxtView = (TextView) mView.findViewById(R.id.fragment_color_spinner);
        mNavColorSetting = (RelativeLayout) mView.findViewById(R.id.nav_color_imv);
        mClearTransformBtn = (Button) mView.findViewById(R.id.transform_clear_all);
        mUIColorSetting = (RelativeLayout) mView.findViewById(R.id.fragment_color_imv);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.nav_color_ibv:
            case R.id.nav_color_imv:
                mCurrentType = COLOR_TYPE.NAV_TYPE;
                showSpinWindow(mNavPopWindow, mNavTxtView);
                break;
            case R.id.ui_color_ibv:
            case R.id.fragment_color_imv:
                mCurrentType = COLOR_TYPE.UI_TYPE;
                showSpinWindow(mUIPopWindow, mUITxtView);
                break;
            case R.id.save_setting:
                saveConfiguration();
                break;
        }
    }

    private ProgressDialog mSaveConfigurationDialog;

    private void saveConfiguration() {
        if (!mIsSavingConfiguration) {
            mSaveConfigurationDialog = ProgressDialog.show(mContext, "", mContext.getString(R.string.configuration_saving), true, false);
            new SaveConfigurationTask().execute();
        }
    }

    private void showSpinWindow(SpinnerPopWindow popView, TextView textView) {
        popView.setWidth(textView.getWidth());
        popView.showAsDropDown(textView);
    }

    @Override
    public void onItemClick(int pos) {
        setHero(pos);
    }

    private void setHero(int pos) {
        if (pos >= 0 && pos <= mColorList.size()) {

            CustomSpinnerData value = mColorList.get(pos);
            if (mCurrentType == COLOR_TYPE.NAV_TYPE) {
                mNavColorValue = pos;
                mNavTxtView.setText(value.toString());
                switch (pos) {
                    case 0:
                        ((MainActivity) mContext).setNavBackgroundResource(R.color.beige);
                        break;
                    case 1:
                        ((MainActivity) mContext).setNavBackgroundResource(R.color.darkslategray);
                        break;
                    case 2:
                        ((MainActivity) mContext).setNavBackgroundResource(R.color.skyblue);
                        break;
                    case 3:
                        ((MainActivity) mContext).setNavBackgroundResource(R.color.darkgray);
                        break;
                    case 4:
                        ((MainActivity) mContext).setNavBackgroundResource(R.color.palegreen);
                        break;
                    case 5:
                        ((MainActivity) mContext).setNavBackgroundResource(R.color.darkorchid);
                        break;
                    case 6:
                        ((MainActivity) mContext).setNavBackgroundResource(R.color.aquamarine);
                        break;
                }
            } else if (mCurrentType == COLOR_TYPE.UI_TYPE) {
                mUIColorValue = pos;
                mUITxtView.setText(value.toString());
                switch (pos) {
                    case 0:
                        ((MainActivity) mContext).setUIBackgroundResource(R.color.beige);
                        break;
                    case 1:
                        ((MainActivity) mContext).setUIBackgroundResource(R.color.darkslategray);
                        break;
                    case 2:
                        ((MainActivity) mContext).setUIBackgroundResource(R.color.skyblue);
                        break;
                    case 3:
                        ((MainActivity) mContext).setUIBackgroundResource(R.color.darkgray);
                        break;
                    case 4:
                        ((MainActivity) mContext).setUIBackgroundResource(R.color.palegreen);
                        break;
                    case 5:
                        ((MainActivity) mContext).setUIBackgroundResource(R.color.darkorchid);
                        break;
                    case 6:
                        ((MainActivity) mContext).setUIBackgroundResource(R.color.aquamarine);
                        break;
                }
            }
        }
    }

    @Override
    public void onChange(SwitchButton sb, boolean state) {
        mProtectedEye = state;
    }

    private enum COLOR_TYPE {NONE, NAV_TYPE, UI_TYPE}

    private COLOR_TYPE mCurrentType = COLOR_TYPE.NONE;

    private final class SaveConfigurationTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... voids) {
            mIsSavingConfiguration = true;
            int status = writeUIParameterConfigureInfo();
            if (status == 1) {
                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            mIsSavingConfiguration = false;
            if (mSaveConfigurationDialog != null && mSaveConfigurationDialog.isShowing()) {
                mSaveConfigurationDialog.dismiss();
            }
            if (aBoolean) {
                ToastUtils.showToast(mContext, mContext.getString(R.string.configuration_save_success));
            } else {
                ToastUtils.showToast(mContext, mContext.getString(R.string.configuration_save_failure));
            }
        }
    }
}
